﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Data;
using DotNetNuke.Entities.Host;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Entities.Tabs;
using DotNetNuke.Entities.Users;
using DotNetNuke.Framework;
using DotNetNuke.Security;
using DotNetNuke.Security.Permissions;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;
using DotNetNuke.Services.Log.EventLog;
using DotNetNuke.UI.Skins;
using DotNetNuke.UI.Skins.Controls;
using DotNetNuke.UI.Utilities;
using DotNetNuke.Web.UI;
using Telerik.Web.UI;
using DataCache = DotNetNuke.Common.Utilities.DataCache;
using Globals = DotNetNuke.Common.Globals;
using iLangl.Customer.DNN.Components;
using DotNetNuke.Entities.Modules.Actions;
using DotNetNuke.Entities.Profile;
using System.Collections;
using iLangl.Customer.DNN.Controls;

using System.Data;
using iLangl.Model;
using iLangl.Customer.DNN.Entities;
using iLangl.Customer;
using iLangl;
using iLangl.Customer.DNN.Managers;
using System.Text;




namespace iLangl.Customer.DNN
{
	public partial class ProjectNew : DnnModuleBase
	{

		#region Properties
		protected List<TabInfo> Tabs
		{
			get
			{
				return TabController.GetPortalTabs(PortalId, Null.NullInteger, false, true, false, true);
			}
		}

		private string SelectedNode
		{
			get
			{
				return (string)ViewState["SelectedNode"];
			}
			set
			{
				ViewState["SelectedNode"] = value;
			}
		}

		#endregion


		#region Content TreeView Functionality
		private void AddAttributes(ref RadTreeNode node, TabInfo tab)
		{

		}

		protected bool Validate()
		{
			bool isValid = true;

			if (ProjectManagerDNN.Instance.GetProjectByName(txtProjectTitle.Text) != null)
			{
				isValid = false;
				valProjectName.IsValid = false;
			}


			return isValid;
		}

		protected void procceed(RadTreeNode node)
		{
			int ContentId = int.Parse(node.Value);
			int lprId = GetLanguageId(node.TreeView.ID);
			dtoContent.ContentRow cr = Content.Content.FindById(ContentId);

			if (cr == null)
				return;

			dtoContent.TranslationContentRow tcr = Content.TranslationContent.FindByLanguagePairIdContentId(lprId, ContentId);


			if (node.Checked)
			{
				if(tcr == null)
					Content.TranslationContent.AddTranslationContentRow(
						Content.Content.FindById(ContentId), 
						Content.LanguagePairs.FindById(lprId),
						false,
						0
						);
			}
			else
			{

				if (tcr != null)
				{
					tcr.IsSelected = true;
				}
			}

			foreach (RadTreeNode childnode in node.Nodes)
			{
				procceed(childnode);
			}
		}


		private void BindTree(ContentPresenter presenter, RadTreeView tree, dtoContent.LanguagePairsRow lpr)
		{
			
			tree.Nodes.Clear();
			tree.TriStateCheckBoxes = true;
			tree.NodeCheck += new RadTreeViewEventHandler(tree_NodeCheck);
			
			var rootNode = new RadTreeNode();
			var strParent = "-1";

			if (Settings["ParentPageFilter"] != null)
			{
				strParent = Convert.ToString(Settings["ParentPageFilter"]);
			}

			if (strParent == "-1")
			{
				rootNode.Text = PortalSettings.PortalName;
				rootNode.ImageUrl = GetIcon(IconManager.IconPortal);
				rootNode.Value = Null.NullInteger.ToString();
				rootNode.Expanded = true;
				rootNode.AllowEdit = false;
				rootNode.EnableContextMenu = false;

				rootNode.Attributes.Add("isPortalRoot", "True");
				AddAttributes(ref rootNode, null);
			}
			else
			{
				var tabController = new TabController();
				var parent = tabController.GetTab(Convert.ToInt32(strParent), -1, false);
				if (parent != null)
				{
					rootNode.Text = parent.TabName;
					rootNode.ImageUrl = GetIcon(IconManager.IconPortal);
					rootNode.Value = parent.TabID.ToString();
					rootNode.Expanded = true;
					rootNode.EnableContextMenu = true;
					rootNode.PostBack = false;
				}
			}

		
			int level = 0;
			Content.Content.DefaultView.RowFilter = String.Format("Level = {0} AND CultureCode = '{1}'", level, presenter.CultureCode);
			Content.Content.DefaultView.Sort = "Title";

			while (Content.Content.DefaultView.Count > 0)
			{
				foreach (DataRowView drv in Content.Content.DefaultView)
				{
					dtoContent.ContentRow cr = (dtoContent.ContentRow)drv.Row;

					RadTreeNode node = null;
					dtoContent.TranslationContentRow tcr = Content.TranslationContent.FindByLanguagePairIdContentId(lpr.Id, cr.Id);

					//Made a refactoring
					if (cr.ContentType == ContentManager.TabType)
					{
						TabInfo tab = (TabInfo)presenter.GetContent(cr);
						
						node = new RadTreeNode { 
							Text = string.Format("{0} {1}", cr.Title, GetNodeStatusIcon(tab))+(tcr == null ? String.Empty : " " + GetTranslateStateIcon((eTranslationState)tcr.State)), 
							Value = cr.Id.ToString(), 
							AllowEdit = true, 
							ImageUrl = GetNodeIcon(tab),
							Checked = (tcr== null ? false: tcr.IsSelected),
							EnableContextMenu = true
						};

						node.Expanded = node.Checked;
					}
					else
					{
						ModuleInfo mi = (ModuleInfo)presenter.GetContent(cr);
						node = new RadTreeNode
						{
							Text = string.Format("{0}", cr.Title) +(tcr == null ? String.Empty : " " + GetTranslateStateIcon((eTranslationState)tcr.State)),
							Value = cr.Id.ToString(),
							AllowEdit = true,
							ImageUrl = GetIcon(IconManager.ModuleIcon),
							Checked = (tcr == null ? false : tcr.IsSelected),
							EnableContextMenu = true
						};
						node.Expanded = node.Checked;
					}

					presenter.AddTreeNode(cr, node);
					
					
					if(cr.ParentId >= 0)
					{
						dtoContent.ContentRow pr = ContentManager.Find(Content, ContentManager.TabType, presenter.CultureCode, cr.ParentId);


						((RadTreeNode)presenter.GetNode(pr)).Nodes.Add(node);
					}
					else
					{
						rootNode.Nodes.Add(node);
					}
				}

				level++;
				Content.Content.DefaultView.RowFilter = String.Format("Level = {0} AND CultureCode = '{1}'", level, presenter.CultureCode);
			}
			
			tree.Nodes.Add(rootNode);

			
			tree.DataBind();
		}

		void tree_NodeCheck(object sender, RadTreeNodeEventArgs e)
		{
			procceed(e.Node);
		}


		#endregion

		#region Data Binding

		public CustomerProject GetProject(CustomerProject project)
		{
			project.Name = txtProjectTitle.Text;
			project.Description = txtDescription.Text;
			project.Product = new Product();
			project.Product.Id = drpProjectProduct.SelectedValue;
			project.WorkArea = new WorkArea();
			project.WorkArea.Id = drpWorkArea.SelectedValue;
			project.IsLockContentDuringTranslation = chkLockContent.Checked;

			ContentPresenter presenter = new ContentPresenter(Content);

			foreach (dtoContent.TranslationContentRow tcr in Content.TranslationContent)
			{
				if (!tcr.IsSelected)
					continue;

				dtoContent.ContentRow cr = Content.Content.FindById(tcr.ContentId);

				ContentEntity content =  (ContentEntity)presenter.GetContent(cr); 

				if(content == null)
				{
					content = ContentManager.Instance.GetContent(cr, this.PortalId);
					presenter.AddContent(cr, content);
					project.AddContent(content);
				}
				
				

				dtoContent.LanguagePairsRow lpr = Content.LanguagePairs.FindById(tcr.LanguagePairId);

				Translation translation = new Translation();
				translation.Id = Guid.NewGuid().ToString();
				translation.LanguagePair = new LanguagePair();
				translation.LanguagePair.SourceLanguage.LanguageId = lpr.SourceLanguage;
				translation.LanguagePair.TargetLanguage.LanguageId = lpr.TargetLanguage;
				translation.Progress = 0;
				//TODO: Support comment
				//translation.Comment = ;
				translation.SourceContent = content;
				translation.Status = TranslationStatuses.Configuration;

				project.AddTranslation(translation);
			}

			return project;
		}
		#endregion


		#region Tabs
		protected void btnConfirm_Click(object sender, EventArgs e)
		{
			try
			{
				//Validate
				CustomerProject project = GetProject(ProjectManagerDNN.Instance.NewProject());

				ProjectManagerDNN.Instance.CreateProject(project);
				btnConfirm.Visible = false;

				ShowSuccessMessage(GetLocalizedString("lblStatus"));
				btnConfirm.Visible = false;
				btnCancel.Visible = false;
				btnPrev.Visible = false;
				btnDone.Visible = true;
				
			}
			catch (System.Exception ex)
			{
				ShowErrorMessage(ex);
			}

			
		}
		

		protected void btnNext_Click(object sender, EventArgs e)
		{
			HttpCookie cookie = Request.Cookies["dnnTabs-tabSettingsForm"];
			if (cookie == null)
				return;

			if (!Validate())
				return;

			int tabId = int.Parse(cookie.Value);

			if (tabId == 0) //Register User
			{
				OpenTranslationsTab();
			}

			if (tabId == 1)
			{
				OpenConfirmationTab();
			}
		
		}

		protected void btnPrev_Click(object sender, EventArgs e)
		{
			HttpCookie cookie = Request.Cookies["dnnTabs-tabSettingsForm"];
			if (cookie == null)
				return;

			int tabId = int.Parse(cookie.Value);

			if (tabId == 1) //Register User
			{
				OpenGeneralTab();
			}

			if (tabId == 2)
			{
				OpenTranslationsTab();
			}
		
		}

		private void OpenGeneralTab()
		{
			btnPrev.Visible = false;
			btnNext.Visible = true;

			HttpCookie myCookie = new HttpCookie("dnnTabs-tabSettingsForm");
			myCookie.HttpOnly = false;

			myCookie.Value = "0";
			Response.Cookies.Add(myCookie);
		}


			

		private void OpenConfirmationTab()
		{
			dnnProjectCreateConfirmation.Visible = true;
			dnnProjectCreateConfirmationDIV.Visible = true;
			btnConfirm.Visible = true;
			btnNext.Visible = false;
			btnPrev.Visible = true;

			ProjectViewReport report = new ProjectViewReport(this);
			CustomerProject project = GetProject(ProjectManagerDNN.Instance.NewProject());
			ProjectReport.InnerHtml = report.GetProjectReport(project);

			HttpCookie myCookie = new HttpCookie("dnnTabs-tabSettingsForm");
			myCookie.HttpOnly = false;

			myCookie.Value = "2";
			Response.Cookies.Add(myCookie);
			
		}

		private void OpenTranslationsTab()
		{
			dnnProjectTranslations.Visible = true;
			dnnProjectTranslationsDIV.Visible = true;
			btnPrev.Visible = true;
			btnConfirm.Visible = false;
			btnNext.Visible = true;

			HttpCookie myCookie = new HttpCookie("dnnTabs-tabSettingsForm");
			myCookie.HttpOnly = false;

			myCookie.Value = "1";
			Response.Cookies.Add(myCookie);
		}

		private void changeTabsVisible(bool flag)
		{
			dnnProjectTranslations.Visible = flag;
			dnnProjectTranslationsDIV.Visible = flag;
			dnnProjectCreateConfirmation.Visible = flag;
			dnnProjectCreateConfirmationDIV.Visible = flag;
			
		}
		#endregion

		#region Page Handler		
		protected override void Page_Init(object sender, EventArgs e)
		{
		}

		protected override void OnInit(EventArgs e)
		{

		}

		protected override void OnLoad(EventArgs e)
		{
			try
			{
				btnCancel.NavigateUrl = Globals.NavigateURL();

				CheckSecurity();

				if (!Page.IsPostBack)
				{
					btnCancel.NavigateUrl = Globals.NavigateURL();
					btnDone.NavigateUrl = Globals.NavigateURL();
					drpSourceLanguages.DataSource = LanguageManager.Instance.GetPortalLanguages(this.PortalId);
					drpSourceLanguages.DataBind();
					drpTargetLanguages.DataSource = LanguageManager.Instance.GetPortalLanguages(this.PortalId);
					drpTargetLanguages.DataBind();

					drpSourceLanguages.SelectedValue = this.PortalSettings.DefaultLanguage;

					changeTabsVisible(false);

					
					BindUser();
					BindTabs();
					BindWorkAreas();
					BindProducts();
					BindProject();
				}
			}
			catch (Exception exc) //Module failed to load
			{
				Exceptions.ProcessModuleLoadException(this, exc);
			}
		}


		

		private ITemplate GetTreeTemplate()
		{
			ContentTreeNode template = new ContentTreeNode();

			template.SourceLanguage = drpSourceLanguages.SelectedValue;
			template.eСontent = Content;
			
			return template;
		}



		private void BindWorkAreas()
		{
			drpWorkArea.DataSource = SettingsManager.Instance.GetWorkAreas();
			drpWorkArea.DataBind();
		}

		private void BindProducts()
		{
			drpProjectProduct.DataSource = SettingsManager.Instance.GetProducts();
			drpProjectProduct.DataBind();
		}

		private void BindProject()
		{
			CustomerProject cp = ProjectManagerDNN.Instance.NewProject();
			lblProjectStatusValue.Text = cp.Status;
		}

		private void BindUser()
		{
			ArrayList users = UserController.GetUsers(this.PortalId);
			UserInfo currentuser = UserController.GetCurrentUserInfo();
			bool isCurrentUserthere = false;
			foreach (UserInfo ui in users)
			{
				if (ui.UserID == currentuser.UserID)
				{
					isCurrentUserthere = true;
					break;
				}
			}

			if (!isCurrentUserthere)
			{
				users.Insert(0, currentuser);
			}

			drpUsers.DataSource = users;
			drpUsers.DataBind();
			drpUsers.SelectedValue = currentuser.UserID.ToString();
		}


		private void CheckSecurity()
		{
			if ((!(TabPermissionController.HasTabPermission("CONTENT"))) && !(ModulePermissionController.HasModulePermission(ModuleConfiguration.ModulePermissions, "CONTENT, EDIT")))
			{
				Response.Redirect(Globals.NavigateURL("Access Denied"), true);
			}
		}

		#endregion

		#region Icons

		private string GetTranslateStateIcon(eTranslationState state)
		{
			StringBuilder result = new StringBuilder();
			String iconmask = "<img src=\"{0}\" class=\"statusicon\" />";

			if ((state & eTranslationState.Commented) == eTranslationState.Commented)
			{
				result.AppendFormat(iconmask, GetIcon(IconManager.iLanglIcon_Commented));
			}

			if ((state & eTranslationState.Customized) == eTranslationState.Customized)
			{
				result.AppendFormat(iconmask, GetIcon(IconManager.iLanglIcon_Customized));
			}

			if ((state & eTranslationState.Locked) == eTranslationState.Locked)
			{
				result.AppendFormat(iconmask, GetIcon(IconManager.iLanglIcon_Locked));
			}

			if ((state & eTranslationState.Ordered) == eTranslationState.Ordered)
			{
				result.AppendFormat(iconmask, GetIcon(IconManager.iLanglIcon_Ordered));
			}

			if ((state & eTranslationState.SourceChanged) == eTranslationState.SourceChanged)
			{
				result.AppendFormat(iconmask, GetIcon(IconManager.iLanglIcon_SourceChanged));
			}

			if ((state & eTranslationState.TargetChanged) == eTranslationState.TargetChanged)
			{
				result.AppendFormat(iconmask, GetIcon(IconManager.iLanglIcon_TargetChanged));
			}

			if ((state & eTranslationState.Translated) == eTranslationState.Translated)
			{
				result.AppendFormat(iconmask, GetIcon(IconManager.iLanglIcon_Translated));
			}

		

			return result.ToString();
		}


		private string GetNodeStatusIcon(TabInfo tab)
		{
			if (tab.DisableLink)
			{
				return "<img src=\"" + GetIcon(IconManager.IconPageDisabled) + "\" class=\"statusicon\" />";
			}

			if (tab.IsVisible == false)
			{
				return "<img src=\"" + GetIcon(IconManager.IconPageHidden) + "\" class=\"statusicon\" />";
			}

			return "";
		}


		private string GetNodeIcon(TabInfo tab)
		{
			if (PortalSettings.HomeTabId == tab.TabID)
			{
				return GetIcon(IconManager.IconHome);
			}

			if (IsSecuredTab(tab))
			{
				if (IsAdminTab(tab))
				{
					return GetIcon(IconManager.AdminOnlyIcon);
				}

				if (IsRegisteredUserTab(tab))
				{
					return GetIcon(IconManager.RegisteredUsersIcon);
				}

				return GetIcon(IconManager.SecuredIcon);
			}

			return GetIcon(IconManager.AllUsersIcon);
		}



		#endregion

		#region Helper Methods
		private static bool IsSecuredTab(TabInfo tab)
		{
			var perms = tab.TabPermissions;
			return perms.Cast<TabPermissionInfo>().All(perm => perm.RoleName != "All Users" || !perm.AllowAccess);
		}

		private bool IsRegisteredUserTab(TabInfo tab)
		{
			var perms = tab.TabPermissions;
			return perms.Cast<TabPermissionInfo>().Any(perm => perm.RoleName == PortalSettings.RegisteredRoleName && perm.AllowAccess);
		}

		private bool IsAdminTab(TabInfo tab)
		{
			var perms = tab.TabPermissions;
			return perms.Cast<TabPermissionInfo>().All(perm => perm.RoleName == PortalSettings.AdministratorRoleName || !perm.AllowAccess);
		}


		#endregion

#region Modules Section
		private List<ModuleInfo> GetChildModules(int tabId, string cultureCode)
		{
			var modules = new List<ModuleInfo>();
			var tabCtrl = new TabController();
			Locale locale = LocaleController.Instance.GetLocale(cultureCode);
			if (locale != null)
			{
				modules = (from kvp in tabCtrl.GetTabByCulture(tabId, PortalSettings.PortalId, locale).ChildModules where !kvp.Value.IsDeleted select kvp.Value).ToList();
			}
			return modules;
		}

		#endregion
		

	
		protected void btnAddLanguage_Click(object sender, EventArgs e)
		{
			string sourceLanguage = drpSourceLanguages.SelectedValue;
			string targetLanguage = drpTargetLanguages.SelectedValue;

			bool isFind = false;
			foreach (dtoContent.LanguagePairsRow lr in Content.LanguagePairs)
			{
				if((lr.SourceLanguage == sourceLanguage) &&(lr.TargetLanguage == targetLanguage))
				{
					ShowWarningMessage(GetLocalizedString("lLanguagePairAlreadyExists"));

					isFind = true;
					
				}
			}

			ContentPresenter presenter = new ContentPresenter(Content);

			if (!isFind)
			{
				presenter.AddLanguagePair(sourceLanguage, targetLanguage);
			}
			

			BindTabs();
		}

		protected void btnRemoveLanguage_Click(object sender, EventArgs e)
		{
			string sourceLanguage = drpSourceLanguages.SelectedValue;
			string targetLanguage = drpTargetLanguages.SelectedValue;

			dtoContent.LanguagePairsRow todelete = null;
			foreach (dtoContent.LanguagePairsRow lr in Content.LanguagePairs)
			{
				if ((lr.SourceLanguage == sourceLanguage) && (lr.TargetLanguage == targetLanguage))
				{
					todelete = lr;
					break;
				}
			}

			if (todelete == null)
			{
				ShowWarningMessage(GetLocalizedString("lLanguagePairNotFound"));
			}

			Content.LanguagePairs.Rows.Remove(todelete);
			ContentPresenter presenter = ContentManager.Instance.GetContent(this.PortalId, this.drpSourceLanguages.SelectedValue, this.drpTargetLanguages.SelectedValue, Content);
			Content = presenter.Content;
			BindTabs();

		}
		protected void BindTabs()
		{
			if (Content == null)
				return;

			rtsLanguages.Tabs.Clear();
			rmpLanguages.PageViews.Clear();
			foreach (dtoContent.LanguagePairsRow lpr in Content.LanguagePairs)
			{
				RadTab tab1 = new RadTab();
				tab1.Text = String.Format("{0}-{1}"
					,Content.Languages.FindByLanguageId(lpr.SourceLanguage).LanguageName
					, Content.Languages.FindByLanguageId(lpr.TargetLanguage).LanguageName
					);

				rtsLanguages.Tabs.Add(tab1);

				tab1.Selected = (lpr.SourceLanguage == drpSourceLanguages.SelectedValue)
				    && (lpr.TargetLanguage == drpTargetLanguages.SelectedValue);

				rtsLanguages.SelectedIndex = tab1.Index;
				rmpLanguages.SelectedIndex = tab1.Index;

				RadPageView pageview = new RadPageView();
				pageview.ID = lpr.Id.ToString();
				rmpLanguages.PageViews.Add(pageview);
				

			}

		}

		protected void RadMultiPage1_PageViewCreated(object sender, RadMultiPageEventArgs e)
		{
			dtoContent.LanguagePairsRow lpr = Content.LanguagePairs.FindById(int.Parse(e.PageView.ID));

			ContentPresenter presenter = ContentManager.Instance.GetContent(this.PortalId, lpr.SourceLanguage, lpr.TargetLanguage, Content);
			Content = presenter.Content;

			RadTreeView tree = new RadTreeView();
			tree.ID = GetLanguageId(lpr);
			tree.OnClientNodeChecked = "ClientNodeChecked";
			tree.CheckBoxes = true;
			BindTree(presenter, tree, lpr);

			RadTreeViewContextMenu menu = new RadTreeViewContextMenu();
			RadMenuItem addComent = new RadMenuItem();
			addComent.Text =GetLocalizedString("lAddComment");
			addComent.Value = "addcoment";
			menu.Items.Add(addComent);

			tree.ContextMenus.Add(menu);
			tree.ContextMenuItemClick += new RadTreeViewContextMenuEventHandler(tree_ContextMenuItemClick);

			e.PageView.Controls.Add(tree);
		}

		void tree_ContextMenuItemClick(object sender, RadTreeViewContextMenuEventArgs e)
		{
			
		}

		private String GetLanguageId(dtoContent.LanguagePairsRow lpr)
		{
			return String.Format("LanguageTree_{0}", lpr.Id);
		}

		private Int32 GetLanguageId(String id)
		{
			return int.Parse(id.Replace("LanguageTree_", String.Empty));
		}

		public dtoContent Content
		{
			get
			{
				dtoContent result = (dtoContent)ViewState["ProjectContent"];

				if (result == null)
				{
					result = new dtoContent();
					ViewState["ProjectContent"] = result;
				}

				return result;
			}
			set
			{
				ViewState["ProjectContent"] = value;
			}
		}

	}
}